<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="圈子名称" prop="circleId">
        <el-select
          v-model="queryParams.circleId"
          placeholder="请选择圈子"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="circle in circleOptions"
            :key="circle.id"
            :label="circle.name"
            :value="circle.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="每日推送时间" prop="pushTime" class="push_time">
        <el-time-picker
          v-model="queryParams.pushTime"
          placeholder="请选择每日推送时间"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          clearable
        ></el-time-picker>
      </el-form-item>
      <el-form-item label="推送功能状态" prop="pushStatus" class="push-status">
        <el-select v-model="queryParams.pushStatus" placeholder="请选择推送功能状态" clearable>
          <el-option
            v-for="dict in pushStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pushSetting:pushSetting:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pushSetting:pushSetting:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pushSetting:pushSetting:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pushSetting:pushSetting:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pushSettingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="圈子名称" align="center" prop="circleId">
        <template #default="scope">
          {{ getCircleNameById(scope.row.circleId) }}
        </template>
      </el-table-column>
      <el-table-column label="每日推送时间" align="center" prop="pushTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.pushTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推送功能状态" align="center" prop="pushStatus">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.pushStatus == 1">开启</el-tag>
          <el-tag type="info" v-else>关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="success" icon="CaretRight" @click="handlePushNow(scope.row)" v-hasPermi="['pushSetting:pushSetting:edit']" :disabled="scope.row.pushStatus != 1">立即推送</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pushSetting:pushSetting:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pushSetting:pushSetting:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改圈子热搜推送设置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="pushSettingRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="圈子名称" prop="circleId" v-if="form.id == null">
          <el-select
            v-model="form.circleId"
            placeholder="请选择圈子"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="circle in circleOptions"
              :key="circle.id"
              :label="circle.name"
              :value="circle.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="每日推送时间" prop="pushTime">
          <el-time-picker
            v-model="form.pushTime"
            placeholder="请选择每日推送时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            clearable
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="推送功能状态" prop="pushStatus">
          <el-radio-group v-model="form.pushStatus">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PushSetting">
import { listPushSetting, getPushSetting, delPushSetting, addPushSetting, updatePushSetting, pushNow } from "@/api/pushSetting/pushSetting";
import { listCircle } from "@/api/circle/circle";

const { proxy } = getCurrentInstance();

const pushSettingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const circleOptions = ref([]); 

// 推送功能状态选项
const pushStatusOptions = ref([
  { value: "0", label: "关闭" },
  { value: "1", label: "开启" }
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    circleId: null,
    pushTime: null,
    pushStatus: null,
  },
  rules: {
    circleId: [
      { required: true, message: "圈子不能为空", trigger: "change" }
    ],
    pushTime: [
      { required: true, message: "每日推送时间不能为空", trigger: "blur" }
    ],
    pushStatus: [
      { required: true, message: "推送功能状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询圈子热搜推送设置列表 */
function getList() {
  loading.value = true;
  listPushSetting(queryParams.value).then(response => {
    pushSettingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 获取圈子列表
function getCircleList() {
  listCircle().then(response => {
    if (response.code === 200 && response.rows) {
      circleOptions.value = response.rows.map(item => ({
        id: item.id,
        name: item.circleName || `圈子${item.id}`
      }));
    } else {
      circleOptions.value = [];
      proxy.$modal.msgError("获取圈子列表失败");
    }
  }).catch(() => {
    circleOptions.value = [];
    proxy.$modal.msgError("获取圈子列表失败");
  });
}

// 添加获取圈子名称的方法
function getCircleNameById(id) {
  if (!id) return '';
  const circle = circleOptions.value.find(item => item.id === id);
  return circle ? circle.name : `圈子${id}`;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    circleId: null,
    pushTime: null,
    pushStatus: 1,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null
  };
  proxy.resetForm("pushSettingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加圈子热搜推送设置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPushSetting(_id).then(response => {
    form.value = response.data;
    form.value.pushStatus = parseInt(form.value.pushStatus);
    open.value = true;
    title.value = "修改圈子热搜推送设置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pushSettingRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePushSetting(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 直接使用选中的圈子ID
        addPushSetting(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除圈子热搜推送设置编号为"' + _ids + '"的数据项？').then(function() {
    return delPushSetting(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 立即推送按钮操作 */
function handlePushNow(row) {
  // 检查推送功能是否开启
  if (row.pushStatus != 1) {
    proxy.$modal.msgError("该圈子的推送功能未开启，无法执行推送");
    return;
  }
  
  const circleName = getCircleNameById(row.circleId);
  proxy.$modal.confirm('确认要立即推送当天的热搜内容到"' + circleName + '"圈子吗？').then(function () {
    return pushNow(row.id);
  }).then(() => {
    proxy.$modal.msgSuccess("推送任务执行成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pushSetting/pushSetting/export', {
    ...queryParams.value
  }, `pushSetting_${new Date().getTime()}.xlsx`)
}

getCircleList();
getList();
</script>
<style scoped>
.push_time :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.push-status :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 80px;
}
.push-status :deep(.el-select) {
  width: 180px; 
}
</style>